import React, { Component } from 'react';
import { Form, Input, Select, message } from 'antd';
import _ from 'lodash';
import Eject from '@/components/Eject';
import * as apis from '@/services/SystemMgr';

const { Option } = Select;
@Form.create()
export default class SetMenu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      typeCode: [],
      treeData: [],
      perType: [],
    };
  }

  /** **
   * 请求字典typeCode
   */
  getDataDictionary = async () => {
    const response = await apis.getDictionaryByTypeCodeUsingGET({
      params: {
        typeCode: 'per_type',
      },
    });
    const response1 = await apis.getDictionaryByTypeCodeUsingGET({
      params: {
        typeCode: 'its_application',
      },
    });
    this.setState({
      perType: response.data,
      typeCode: response1.data,
    });
  };

  // 点击弹出
  handleShowDrawer = async () => {
    const data = await apis.getSysPermissionTreeUsingGET({ params: {} });
    if (data.code === 1) {
      this.setState({
        treeData: data.data,
      });
    }
    this.getDataDictionary();
    this.setState({
      visible: true,
    });
  };

  // 点击收起
  handleOnClose = () => {
    this.setState({
      visible: false,
    });
  };

  // 树状转成平行
  getTreeData = (data, treeData) => {
    data.forEach(value => {
      treeData.push(value);
      if (value.childMenu.length > 0) {
        this.getTreeData(value.childMenu, treeData);
      }
    });
    return treeData;
  };

  // 找出父级菜单
  screenParentMenu = (value, data) => {
    if (value === '编辑') {
      if (data.parentCode !== '') {
        const newData = this.getTreeData(this.state.treeData, []);
        const perName = _.filter(newData, e => e.perCode === data.parentCode);
        return perName.length > 0 ? perName[0].perName : '';
      }
      return '';
    }
    return data.perName;
  };

  handleOkBtnClick = () => {
    this.handleSubmit();
  };

  // 点击提交
  handleSubmit = () => {
    const { form, value, record } = this.props;
    const { typeCode } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        const itsApplicationName = _.filter(typeCode, data => data.dict_code === values.subApp)[0]
          .dict_name;
        const params = {
          itsApplicationName,
          itsApplicationCode: values.subApp,
          parentCode: '',
          perButton: '',
          perCode: values.perCode,
          perEvent: '',
          // perIcon: values.menuIcon ? values.menuIcon : '',
          perIcon: '',
          perLink: '',
          perMenu: '',
          perName: values.menuName,
          perTab: '',
          perType: values.menuType,
          perUrl: values.url,
          routeId: '',
          routeName: '',
          sort: values.sort,
        };
        if (value === '编辑') {
          params.id = record.id;
          params.parentCode = record.parentCode;
        }
        if (value === '新增' && record) {
          params.parentCode = record.perCode;
        }
        const url =
          value === '新增' ? 'createSysPermissionUsingPOST' : 'updateSysPermissionUsingPUT';
        apis[url]({ data: params }).then(data => {
          if (data.code === 1) {
            message.success(data.message);
            this.props.upData();
            this.setState({
              visible: false,
            });
          }
        });
      }
    });
  };

  render() {
    const { btnType, value, title, record } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { typeCode, perType } = this.state;
    return (
      <Eject
        btnType={btnType}
        value={value}
        title={title}
        width={550}
        showDrawer={this.handleShowDrawer}
        handleOkBtnClick={this.handleOkBtnClick}
        onClose={this.handleOnClose}
        visible={this.state.visible}
        modelJsx={
          <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} onSubmit={this.handleSubmit}>
            <Form.Item label="类型">
              {getFieldDecorator('menuType', {
                initialValue: record && record.perType ? record.perType : '1',
                rules: [{ required: true }],
              })(
                <Select>
                  {_.map(perType, element => (
                    <Option value={element.dict_value} key={element.dict_value}>
                      {element.dict_name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="父级">
              {getFieldDecorator('parentMenu', {
                initialValue: record ? this.screenParentMenu(value, record) : '',
              })(<Input disabled />)}
            </Form.Item>
            <Form.Item label="名称">
              {getFieldDecorator('menuName', {
                initialValue: record && value === '编辑' ? record.perName : '',
                rules: [{ required: true, message: '名称不能为空!', whitespace: true }],
              })(<Input placeholder="请输入名称" />)}
            </Form.Item>
            {/* <Form.Item label="图标">
              {getFieldDecorator('menuIcon', {
                rules: [{ required: false }],
              })(
                <Select
                  allowClear
                  placeholder="请选择"
                  disabled={!!(record && record.perType !== '1')}
                >
                  <Option value="solution">
                    <Icon type="solution" />
                  </Option>
                  <Option value="robot">
                    <Icon type="robot" />
                  </Option>
                  <Option value="table">
                    <Icon type="table" />
                  </Option>
                  <Option value="monitor">
                    <Icon type="monitor" />
                  </Option>
                  <Option value="euro">
                    <Icon type="euro" />
                  </Option>
                </Select>,
              )}
            </Form.Item> */}
            <Form.Item label="所属应用">
              {getFieldDecorator('subApp', {
                initialValue: record && value === '编辑' ? record.itsApplicationCode : '',
                rules: [{ required: true, message: '所属应用为必选，请选择!', whitespace: true }],
              })(
                <Select placeholder="请选择" allowClear>
                  {typeCode.map(v => (
                    <Option value={v.dict_value} key={v.dict_value}>
                      {v.dict_name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="URL">
              {getFieldDecorator('url', {
                initialValue: record && value === '编辑' ? record.perUrl : '',
                rules: [{ message: '不能为空!' }],
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="编码">
              {getFieldDecorator('perCode', {
                initialValue: record && value === '编辑' ? record.perCode : '',
                rules: [{ required: true, message: '编码不能为空!' }],
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="排序">
              {getFieldDecorator('sort', {
                initialValue: record && value === '编辑' ? record.sort : '',
                rules: [{ required: true, message: '排序值不能为空!' }],
              })(<Input placeholder="请输入" />)}
            </Form.Item>
          </Form>
        }
      />
    );
  }
}
